package org.looop.studio.noots.document.handler;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.lang.ClassUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.document.Document;
import org.looop.studio.noots.document.DocumentHandler;
import org.looop.studio.noots.document.FileHandler;
import org.looop.studio.noots.document.FileHandlerException;

public class ExtensionFileHandler implements FileHandler {

	private Properties handlerProps;
	
	public ExtensionFileHandler(Properties props){
		handlerProps = props;
	}
	
	@Override
	public Document getDocument(File file) throws FileHandlerException {
		Document doc = null;
		String name = file.getName();
		int dotIndex = name.lastIndexOf(".");
		if(dotIndex > 0 && dotIndex < name.length()){
			String ext = name.substring(dotIndex + 1, name.length());
			String handlerClassName = handlerProps.getProperty(ext);
			if(StringUtils.isNotBlank(handlerClassName)){
				try{
					DocumentHandler handler = (DocumentHandler)ClassUtils.getClass(handlerClassName).newInstance();
					return handler.getDocument(new FileInputStream(file));
				}catch(Exception e){
					throw new FileHandlerException(e);
				}
			}
		}
		return null;
	}
	
	public static void main(String[] args) throws Exception {
		String file = "";
		String handlerConfig = "handlerConfig.prop";
		Properties props = new Properties();
		props.load(new FileInputStream(handlerConfig));
		
		ExtensionFileHandler fileHandler = new ExtensionFileHandler(props);
		Document doc = fileHandler.getDocument(new File(file));
	}

}
